<template>
  <div class="marketing-container">
    <!-- 左侧场景选择区域 -->
    <div class="left-panel">
      <div class="panel-header">
        <div class="tab-buttons">
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'scenario' }"
            @click="activeTab = 'scenario'"
          >
            营销场景
          </button>
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'content' }"
            @click="activeTab = 'content'"
          >
            自媒体文案
          </button>
        </div>
      </div>

      <div class="panel-content">
        <div v-if="activeTab === 'scenario'" class="scenario-content">
          <div class="scenario-options">
            <div class="checkbox-section">
              <div class="checkbox-group">
                <div class="checkbox-item">
                  <a-checkbox
                    v-model:checked="formState.logo_enabled"
                    :disabled="true"
                    >公司LOGO</a-checkbox
                  >
                  <div class="upload-section">
                    <a-upload-dragger
                      v-model:fileList="fileList1"
                      name="file"
                      :multiple="false"
                      :max-count="1"
                      :customRequest="customUpload1"
                      @change="handleChange1"
                      @drop="handleDrop1"
                      :disabled="formState.logo_url.length > 0"
                    >
                      <a-button
                        type="primary"
                        class="upload-btn"
                        :disabled="formState.logo_url.length > 0"
                      >
                        <UploadOutlined />
                        选择图片
                      </a-button>
                    </a-upload-dragger>
                    <div
                      v-if="formState.logo_url.length > 0"
                      class="image-preview"
                    >
                      <div
                        v-for="(url, index) in formState.logo_url"
                        :key="index"
                        class="preview-item"
                      >
                        <img
                          :src="url"
                          alt="公司LOGO预览"
                          class="preview-image"
                        />
                        <button
                          class="delete-btn"
                          @click="deleteImage('logo_url', index)"
                          title="删除图片"
                        >
                          <svg
                            width="12"
                            height="12"
                            viewBox="0 0 12 12"
                            fill="currentColor"
                          >
                            <path
                              d="M9 3L3 9M3 3l6 6"
                              stroke="currentColor"
                              stroke-width="1.5"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                            />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="checkbox-item">
                  <a-checkbox
                    v-model:checked="formState.plat_logo_enabled"
                    :disabled="true"
                    >平台LOGO</a-checkbox
                  >
                  <div class="upload-section">
                    <a-upload-dragger
                      v-model:fileList="fileList2"
                      name="file"
                      :multiple="false"
                      :max-count="1"
                      :customRequest="customUpload2"
                      @change="handleChange2"
                      @drop="handleDrop2"
                      :disabled="formState.plat_logo_url.length > 0"
                    >
                      <a-button
                        type="primary"
                        class="upload-btn"
                        :disabled="formState.plat_logo_url.length > 0"
                      >
                        <UploadOutlined />
                        选择图片
                      </a-button>
                    </a-upload-dragger>
                    <div
                      v-if="formState.plat_logo_url.length > 0"
                      class="image-preview"
                    >
                      <div
                        v-for="(url, index) in formState.plat_logo_url"
                        :key="index"
                        class="preview-item"
                      >
                        <img
                          :src="url"
                          alt="平台LOGO预览"
                          class="preview-image"
                        />
                        <button
                          class="delete-btn"
                          @click="deleteImage('plat_logo_url', index)"
                          title="删除图片"
                        >
                          <svg
                            width="12"
                            height="12"
                            viewBox="0 0 12 12"
                            fill="currentColor"
                          >
                            <path
                              d="M9 3L3 9M3 3l6 6"
                              stroke="currentColor"
                              stroke-width="1.5"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                            />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="checkbox-item">
                  <a-checkbox
                    v-model:checked="formState.equipment_enabled"
                    :disabled="true"
                    >实验仪器图片</a-checkbox
                  >
                  <div class="upload-section">
                    <a-upload-dragger
                      v-model:fileList="fileList3"
                      name="file"
                      :multiple="false"
                      :max-count="1"
                      :customRequest="customUpload3"
                      @change="handleChange3"
                      @drop="handleDrop3"
                      :disabled="formState.equipment_url.length > 0"
                    >
                      <a-button
                        type="primary"
                        class="upload-btn"
                        :disabled="formState.equipment_url.length > 0"
                      >
                        <UploadOutlined />
                        选择图片
                      </a-button>
                    </a-upload-dragger>
                    <div
                      v-if="formState.equipment_url.length > 0"
                      class="image-preview"
                    >
                      <div
                        v-for="(url, index) in formState.equipment_url"
                        :key="index"
                        class="preview-item"
                      >
                        <img
                          :src="url"
                          alt="实验仪器图片预览"
                          class="preview-image"
                        />
                        <button
                          class="delete-btn"
                          @click="deleteImage('equipment_url', index)"
                          title="删除图片"
                        >
                          <svg
                            width="12"
                            height="12"
                            viewBox="0 0 12 12"
                            fill="currentColor"
                          >
                            <path
                              d="M9 3L3 9M3 3l6 6"
                              stroke="currentColor"
                              stroke-width="1.5"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                            />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="checkbox-item">
                  <a-checkbox
                    v-model:checked="formState.contact_enabled"
                    :disabled="true"
                    >联系方式</a-checkbox
                  >
                  <div class="contact-input">
                    <a-input
                      v-model:value="formState.contact_text"
                      placeholder="请输入联系方式"
                    />
                  </div>
                </div>
                <div class="checkbox-item">
                  <a-checkbox
                    v-model:checked="formState.introduce_enabled"
                    :disabled="true"
                    >输入介绍文字</a-checkbox
                  >
                  <div class="contact-input">
                    <a-input
                      v-model:value="formState.introduce"
                      placeholder="请输入介绍文字"
                    />
                  </div>
                  <!-- <div class="upload-section">
                    <a-upload-dragger v-model:fileList="fileList" name="file" :multiple="false" :max-count="1"
                      :customRequest="customUpload" @change="handleChange" @drop="handleDrop"
                      :disabled="formState.other_image_url.length > 0">
                      <a-button type="primary" class="upload-btn" :disabled="formState.other_image_url.length > 0">
                        <UploadOutlined />
                        选择图片
                      </a-button>
                    </a-upload-dragger>
                    <div v-if="formState.other_image_url.length > 0" class="image-preview">
                      <div v-for="(url, index) in formState.other_image_url" :key="index" class="preview-item">
                        <img :src="url" alt="其他图片预览" class="preview-image" />
                        <button class="delete-btn" @click="deleteImage('other_image_url', index)" title="删除图片">
                          <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                            <path d="M9 3L3 9M3 3l6 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
                              stroke-linejoin="round" />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div> -->
                </div>
              </div>
            </div>

            <!-- <div class="custom-input-section">
              <textarea v-model="formState.prompt" placeholder="请输入自定义营销场景" class="scenario-textarea-input"></textarea>
            </div> -->
          </div>
        </div>

        <div v-if="activeTab === 'content'" class="content-section">
          <div class="input-section">
            <textarea
              v-model="formState.prompt"
              placeholder="请输入自媒体文案内容"
              class="scenario-textarea"
            ></textarea>
          </div>
        </div>
      </div>

      <!-- 左侧面板底部操作区域 -->
      <div class="left-panel-actions">
        <div
          class="action-buttons"
          :class="{ 'center-mode': activeTab === 'scenario' }"
        >
          <template v-if="activeTab === 'scenario'">
            <button class="generate-poster-btn" @click="generatePoster">
              生成海报
            </button>
          </template>
          <template v-else>
            <button
              class="action-btn settings-btn"
              data-tooltip="AI参数配置"
              @click="openConfigDialog"
            ></button>
            <button
              class="action-btn send-btn"
              data-tooltip="发送"
              @click="generateContent"
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="currentColor"
              >
                <path
                  d="M15.854.146a.5.5 0 01.11.54l-5.819 14.547a.75.75 0 01-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 01.124-1.33L15.314.037a.5.5 0 01.54.11z"
                />
              </svg>
            </button>
          </template>
        </div>
      </div>
    </div>

    <!-- 右侧内容生成区域 -->
    <div class="right-panel">
      <div class="content-area">
        <!-- 营销场景的空状态 -->
        <div v-if="activeTab === 'scenario'" class="empty-state">
          <template v-if="!PosterImage">
          <div class="empty-icon">
            <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
              <rect
                x="16"
                y="20"
                width="32"
                height="24"
                rx="2"
                fill="#E8E8E8"
              />
              <circle cx="24" cy="28" r="2" fill="#BFBFBF" />
              <path d="M28 32L32 28L40 36H20L28 32Z" fill="#BFBFBF" />
            </svg>
          </div>
          <p class="empty-text">暂无数据内容生成上传</p>
          </template>
          <img class="post-image" :src="PosterImage" />
        </div>

        <!-- 自媒体文案的内容区域 -->
        <div v-if="activeTab === 'content'" class="content-generation-area">
          <div class="content-header">
            <h3>AI内容生成</h3>
          </div>
          <div class="content-body">
            <div class="input-prompt-section">
              <textarea
                v-model="contentPrompt"
                placeholder="AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容..."
                class="content-prompt-textarea"
                readonly
              ></textarea>
            </div>
            <div class="button-container">
              <a-button
                type="primary"
                class="ai-voice-btn"
                @click="openVoiceDialog"
              >
                AI配音
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- AI参数配置对话框 -->
  <a-modal
    v-model:open="configDialogVisible"
    title="AI参数配置"
    width="600px"
    centered
    @ok="closeConfigDialog"
    @cancel="closeConfigDialog"
  >
    <div class="config-content">
      <a-form layout="vertical">
        <a-form-item>
          <a-textarea
            v-model:value="systemPrompt"
            :rows="4"
            placeholder="请输入系统提示词，用于指导AI的行为和风格"
          />
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <a-button @click="closeConfigDialog">取消</a-button>
      <a-button type="primary" @click="saveConfig">保存</a-button>
    </template>
  </a-modal>

  <!-- AI配音对话框 -->
  <a-modal
    v-model:open="voiceDialogVisible"
    title="AI配音"
    width="640px"
    centered
    :footer="null"
    @cancel="closeVoiceDialog"
  >
    <div class="voice-dialog-content">
      <!-- 音色选择区域 -->
      <div class="voice-selection">
        <div
          class="voice-option"
          :class="{ active: selectedVoiceType === 'male' }"
          @click="selectVoiceType('male')"
        >
          <div class="voice-avatar">
            <img src="@/assets/Nan.png" alt="男士音色" />
          </div>
          <div class="voice-info">
            <div class="voice-title">男士音色</div>
            <div class="voice-subtitle">Men's tone</div>
          </div>
          <div class="voice-check" v-if="selectedVoiceType === 'male'">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <circle cx="10" cy="10" r="10" fill="#1890ff" />
              <path
                d="M6 10L8.5 12.5L14 7"
                stroke="white"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </div>
        </div>

        <div
          class="voice-option"
          :class="{ active: selectedVoiceType === 'female' }"
          @click="selectVoiceType('female')"
        >
          <div class="voice-avatar">
            <img src="@/assets/Nv.png" alt="女士音色" />
          </div>
          <div class="voice-info">
            <div class="voice-title">女士音色</div>
            <div class="voice-subtitle">Ladies' tone</div>
          </div>
          <div class="voice-check" v-if="selectedVoiceType === 'female'">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <circle cx="10" cy="10" r="10" fill="#1890ff" />
              <path
                d="M6 10L8.5 12.5L14 7"
                stroke="white"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </div>
        </div>
      </div>

      <!-- 文本内容区域 -->
      <div class="voice-content">
        <textarea
          v-model="contentPrompt"
          class="voice-textarea"
          placeholder="AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容AI大语言模型回复的自媒体文案内容..."
        ></textarea>

        <!-- 语音试听组件 -->
        <VoicePreview
          v-if="contentPrompt.trim()"
          :text="contentPrompt"
          :voice-type="selectedVoiceType"
          :show-actions="false"
          ref="voicePreviewRef"
          @play-start="onVoicePlayStart"
          @play-end="onVoicePlayEnd"
          @play-error="onVoicePlayError"
        />
      </div>

      <!-- 底部操作按钮 -->
      <div class="voice-actions">
        <!-- 当没有内容时显示生成和取消按钮 -->
        <template v-if="!contentPrompt.trim()">
          <a-button @click="closeVoiceDialog" class="action-button"
            >取消</a-button
          >
          <a-button
            type="primary"
            @click="generateAiContent"
            class="action-button primary-button"
            :loading="isGenerating"
            >生成</a-button
          >
        </template>
        <!-- 当有内容时显示重新生成、试听、下载按钮 -->
        <template v-else>
          <a-button @click="regenerateVoice" class="action-button"
            >重新生成</a-button
          >
          <a-button @click="handleVoicePreview" class="action-button"
            >试听</a-button
          >
          <a-button
            type="primary"
            @click="handleVoiceDownload"
            class="action-button primary-button"
            >下载</a-button
          >
        </template>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive } from "vue";
import { message } from "ant-design-vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import systemApi from "@/api/system";
import marketingApi from "@/api/marketing";
import VoicePreview from "./voice-preview/VoicePreview.vue";
// 响应式数据
const activeTab = ref("scenario"); // 默认激活营销场景标签
const scenarioInput = ref("");
const prompt = ref("");
const contentPrompt = ref(""); // 右侧内容描述

const fileList = ref([]);
const fileList1 = ref([]);
const fileList2 = ref([]);
const fileList3 = ref([]);
const configDialogVisible = ref(false); // 控制AI参数配置对话框显示
const voiceDialogVisible = ref(false); // 控制AI配音对话框显示
const selectedVoiceType = ref("male"); // 选中的音色类型
const isGenerating = ref(false); // 控制生成按钮加载状态
const currentAiArticleId = ref(""); // 存储当前的ai_article_id
const voicePreviewRef = ref(null); // 语音预览组件引用
const isVoicePlaying = ref(false); // 语音播放状态
// const isVoiceLoading = ref(false); // 语音加载状态

// AI配置参数
const selectedModel = ref("gpt-3.5");
const temperature = ref(0.7);
const maxTokens = ref(2000);
const systemPrompt = ref("");
const customParams = ref("");
const formState = reactive({
  prompt: "", //自定义营销场景
  contact_text: "", //联系方式文案
  logo_url: [], //公司logo图片url数组
  plat_logo_url: [], // 平台logo图片url数组
  equipment_url: [], //实验仪器图片url数组
  other_image_url: [], //其他图片url数组
  introduce: "",

  // 复选框状态
  logo_enabled: true, // 启用公司logo
  plat_logo_enabled: true, // 启用平台logo
  equipment_enabled: true, // 启用实验仪器图片
  contact_enabled: true, // 启用联系方式
  other_image_enabled: false, // 启用其他图片
  introduce_enabled: true, // 启用公司介绍
});
// 打开AI参数配置对话框
const openConfigDialog = () => {
  configDialogVisible.value = true;
};

// 关闭AI参数配置对话框
const closeConfigDialog = () => {
  configDialogVisible.value = false;
};

// 保存AI配置
const saveConfig = () => {
  // 这里可以添加保存配置到后端的逻辑
  console.log("保存配置:", {
    model: selectedModel.value,
    temperature: temperature.value,
    maxTokens: maxTokens.value,
    systemPrompt: systemPrompt.value,
    customParams: customParams.value,
  });
  message.success("配置保存成功！");
  configDialogVisible.value = false;
};

//  预览图片
const customUpload = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error("上传失败"));
    }
  } catch (error) {
    console.error("图片文件上传失败:", error);
    onError(error);
  }
};

const handleChange = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 图片文件上传成功`);
    // 将图片URL设置到formState的other_image_url数组（只保存一张）
    if (info.file.response && info.file.response.url) {
      formState.other_image_url = [info.file.response.url];
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 图片文件上传失败`);
  }
};
function handleDrop(e) {
  console.log("handleChange", e.dataTransfer.files);
}
// ============================================================================
//  预览图片
const customUpload1 = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error("上传失败"));
    }
  } catch (error) {
    console.error("图片文件上传失败:", error);
    onError(error);
  }
};

const handleChange1 = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 图片文件上传成功`);
    // 将图片URL设置到formState的logo_url数组（只保存一张）
    if (info.file.response && info.file.response.url) {
      formState.logo_url = [info.file.response.url];
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 图片文件上传失败`);
  }
};
function handleDrop1(e) {
  console.log("handleChange", e.dataTransfer.files);
}
// ===============================================================================
//  预览图片
const customUpload2 = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error("上传失败"));
    }
  } catch (error) {
    console.error("图片文件上传失败:", error);
    onError(error);
  }
};

const handleChange2 = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 图片文件上传成功`);
    // 将图片URL设置到formState的plat_logo_url数组（只保存一张）
    if (info.file.response && info.file.response.url) {
      formState.plat_logo_url = [info.file.response.url];
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 图片文件上传失败`);
  }
};
function handleDrop2(e) {
  console.log("handleChange", e.dataTransfer.files);
}
// ========================================================================
//  预览图片
const customUpload3 = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error("上传失败"));
    }
  } catch (error) {
    console.error("图片文件上传失败:", error);
    onError(error);
  }
};

const handleChange3 = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 图片文件上传成功`);
    // 将图片URL设置到formState的equipment_url数组（只保存一张）
    if (info.file.response && info.file.response.url) {
      formState.equipment_url = [info.file.response.url];
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 图片文件上传失败`);
  }
};

function handleDrop3(e) {
  console.log("handleChange", e.dataTransfer.files);
}

// 删除图片函数
const deleteImage = (fieldName, index) => {
  formState[fieldName].splice(index, 1);
  // 同时删除对应的文件列表项
  switch (fieldName) {
    case "logo_url":
      if (fileList1.value[index]) {
        fileList1.value.splice(index, 1);
      }
      break;
    case "plat_logo_url":
      if (fileList2.value[index]) {
        fileList2.value.splice(index, 1);
      }
      break;
    case "equipment_url":
      if (fileList3.value[index]) {
        fileList3.value.splice(index, 1);
      }
      break;
    case "other_image_url":
      if (fileList.value[index]) {
        fileList.value.splice(index, 1);
      }
      break;
  }
  message.success("图片删除成功");
};
// ========================================================================
// 打开AI配音对话框
const openVoiceDialog = () => {
  voiceDialogVisible.value = true;
};

// 关闭AI配音对话框
const closeVoiceDialog = () => {
  // 重置语音预览组件状态
  if (voicePreviewRef.value) {
    voicePreviewRef.value.reset();
  }

  voiceDialogVisible.value = false;
  contentPrompt.value = ""; // 重置文本内容
  isGenerating.value = false; // 重置生成状态
  currentAiArticleId.value = ""; // 重置ai_article_id
  isVoicePlaying.value = false; // 重置播放状态
  // isVoiceLoading.value = false; // 重置加载状态
};

// 选择音色类型
const selectVoiceType = (type) => {
  console.log("选择的音色类型:", type);
  selectedVoiceType.value = type;
};

// 生成AI内容
const generateAiContent = async () => {
  try {
    isGenerating.value = true;
    message.loading("正在生成内容...", 0);

    // 如果没有ai_article_id，先调用CreateAiArticle接口
    if (!currentAiArticleId.value) {
      const createResponse = await marketingApi.CreateAiArticle({
        prompt: formState.prompt || "生成自媒体文案内容",
      });

      if (createResponse && createResponse.ai_article_id) {
        currentAiArticleId.value = createResponse.ai_article_id;
      } else {
        message.destroy();
        message.error("创建文章失败，请重试");
        return;
      }
    }

    // 调用GenerateContentForAiArticle接口
    const response = await marketingApi.GenerateContentForAiArticle({
      ai_article_id: currentAiArticleId.value,
    });

    message.destroy();
    console.log(response, "生成自媒体文案");
    if (response) {
      // 尝试多个可能的字段名
      const generatedContent =
        response.ai_generated_content ||
        response.content ||
        response.prompt ||
        response.data ||
        "生成的自媒体文案内容";
      contentPrompt.value = generatedContent;
      console.log("设置的内容:", generatedContent);
      console.log("contentPrompt.value:", contentPrompt.value);
      message.success("内容生成成功!");
    } else {
      message.error(response?.message || "内容生成失败，请重试");
    }
  } catch (error) {
    message.destroy();
    console.error("内容生成错误:", error);
    message.error("内容生成失败，请检查网络连接后重试");
  } finally {
    isGenerating.value = false;
  }
};

// 重新生成
const regenerateVoice = async () => {
  contentPrompt.value = ""; // 清空当前内容
  await generateAiContent(); // 重新调用生成函数
};

// 语音预览处理方法
const handleVoicePreview = async () => {
  if (!contentPrompt.value.trim()) {
    console.log("内容为空，显示警告");
    message.warning("请先生成内容后再试听");
    return;
  }

  if (voicePreviewRef.value) {
    try {
      await voicePreviewRef.value.play();
    } catch (error) {
      console.error("语音预览失败:", error);
    }
  }
};

// 语音下载处理方法
const handleVoiceDownload = async () => {
  if (!contentPrompt.value.trim()) {
    message.warning("请先生成内容后再下载");
    return;
  }

  if (voicePreviewRef.value) {
    try {
      await voicePreviewRef.value.download();
    } catch (error) {
      console.error("语音下载失败:", error);
    }
  }
};

// 语音播放开始事件
const onVoicePlayStart = () => {
  isVoicePlaying.value = true;
  // isVoiceLoading.value = true;
};

// 语音播放结束事件
const onVoicePlayEnd = () => {
  console.log("语音播放结束事件触发");
  isVoicePlaying.value = false;
  // isVoiceLoading.value = false;
};

// 语音播放错误事件
const onVoicePlayError = (error) => {
  isVoicePlaying.value = false;
  // isVoiceLoading.value = false;
  message.error("音频播放出错");
  console.error("语音播放错误:", error);
};

// 下载
// 生成内容
const generateContent = async () => {
  if (!formState.prompt.trim()) {
    message.warning("请先输入自媒体文案内容");
    return;
  }

  try {
    message.loading("正在生成内容...", 0);

    // 调用CreateAiArticle接口
    const response = await marketingApi.CreateAiArticle({
      prompt: formState.prompt,
    });

    message.destroy();
    console.log(response, "文案内容");
    if (response) {
      contentPrompt.value =
        response.ai_generated_content || "生成的自媒体文案内容";
      message.success("内容生成成功!");
    } else {
      message.error(response?.message || "内容生成失败，请重试");
    }
  } catch (error) {
    message.destroy();
    console.error("内容生成错误:", error);
    message.error("内容生成失败，请检查网络连接后重试");
  }
};

// 文件上传前的处理
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("只能上传 JPG/PNG 格式的图片!");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小不能超过 2MB!");
    return false;
  }
  message.success("图片上传成功!");
  return false; // 阻止自动上传
};
const PosterImage = ref(null);
// 生成海报
const generatePoster = async () => {
  if (
    !formState.prompt.trim() &&
    !formState.logo_enabled &&
    !formState.plat_logo_enabled &&
    !formState.equipment_enabled &&
    !formState.contact_enabled &&
    !formState.introduce_enabled
  ) {
    message.warning("请输入自定义营销场景或选择至少一个营销选项");
    return;
  }
  if (!formState.contact_text) {
    message.warning("请填写联系方式文案");
    return;
  }
  if (!formState.equipment_url) {
    message.warning("请上传设备图片");
    return;
  }
  if (!formState.introduce) {
    message.warning("请填写设备介绍文案");
    return;
  }
  if (!formState.plat_logo_url[0]) {
    message.warning("请上传平台logo");
    return;
  }
  if (!formState.logo_url[0]) {
    message.warning("请上传logo");
    return;
  }

  try {
    // 构建请求数据
    const requestData = {
      prompt: formState.prompt, // 自定义营销场景作为prompt
      contact_text: formState.contact_text, // 联系方式文案
      logo_url: formState.logo_url[0],
      plat_logo_url: formState.plat_logo_url[0],
      equipment_url: formState.equipment_url[0],
      introduce: formState.introduce,
      // other_image_url: formState.other_image_url,
      // 复选框状态
      logo_enabled: formState.logo_enabled,
      plat_logo_enabled: formState.plat_logo_enabled,
      equipment_enabled: formState.equipment_enabled,
      contact_enabled: formState.contact_enabled,
      introduce_enabled: formState.introduce_enabled,
      enabled: true,
    };

    message.loading("正在生成海报...", 0);

    // 调用海报生成接口
    const response = await marketingApi.AiPosterCreate(requestData);
    console.log(response, "生成海报结果");
    message.destroy();

    if (response && response.ai_poster_id) {
      message.success("海报生成成功!");

      // 使用ai_poster_id调用GeneratePosterImage接口
      try {
        message.loading("正在生成海报图片...", 0);
        const posterImageResponse = await marketingApi.GeneratePosterImage({
          ai_poster_id: response.ai_poster_id,
        });
        message.destroy();
        console.log(posterImageResponse, "GeneratePosterImage返回的数据");

        if (posterImageResponse) {
          PosterImage.value = posterImageResponse.image_url;
          message.success("海报图片生成成功!");

        } else {
          PosterImage.value = null;
          message.error("海报图片生成失败");
        }
      } catch (imageError) {
        message.destroy();
        PosterImage.value = null;
        console.error("生成海报图片错误:", imageError);
        message.error("海报图片生成失败，请重试");
      }
    } else {
      message.error(response?.message || "海报生成失败，请重试");
    }
  } catch (error) {
    message.destroy();
    console.error("海报生成错误:", error);
    message.error("海报生成失败，请检查网络连接后重试");
  }
};
</script>

<style scoped lang="less">
@import "./index.less";

/* 图片预览样式 */
.image-preview {
  margin-top: 12px;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.preview-item {
  position: relative;
  display: inline-block;
}
.post-image{
  max-width:100%;
  height:100%;
}
.preview-image {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.delete-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.delete-btn:hover {
  background-color: #ff7875;
  transform: scale(1.1);
}
</style>
